package com.example.lirisheng.springbootfinalexperiment.security.provider;

import com.example.lirisheng.springbootfinalexperiment.entity.Users;
import com.example.lirisheng.springbootfinalexperiment.repositories.UserRoleRepository;
import com.example.lirisheng.springbootfinalexperiment.repositories.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    UsersRepository usersRepository;

    @Autowired
    UserRoleRepository userRoleRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String)authentication.getPrincipal();
        String password = (String)authentication.getCredentials();
        Users users = usersRepository.findByUsername(username);
        if(users==null){
            throw  new UsernameNotFoundException("没有该账号,请注册");
        }
        if(!passwordEncoder.matches(password,users.getPassword())){
            throw  new BadCredentialsException("密码不正确");
        }
        if(users.getEnabled()==0){
            throw  new LockedException("账号被锁");
        }
        Set<String> roles= userRoleRepository.findRoleByUserId(users.getId());
        Set<SimpleGrantedAuthority> simpleGrantedAuthorities = new HashSet<>();
        roles.stream().forEach(out->simpleGrantedAuthorities.add(new SimpleGrantedAuthority(out)));
        User user = new User(users.getUsername(),users.getPassword(),simpleGrantedAuthorities);
        return new UsernamePasswordAuthenticationToken(user,null,simpleGrantedAuthorities);

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }

}
